<?php

namespace app\common;

use Firebase\JWT\JWT;

class Token
{
    /**
     * 获取token
     * @param $uid 用户id
     * @return string $jwt token字符串
     */
    public function getToken($uid)
    {
        $token = [
            'iat' => time(),
            'exp' => time() + 60 * 60 * 24 * 7,
            'uid' => $uid
        ];
        $jwt = JWT::encode($token, config('jwt.key'));
        return $jwt;
    }

    /**
     * @param $jwt  传入token字符串
     * @return int|object 返回0为token过期，返回 $decoded 为解密数据
     */
    public function getTokenData($jwt)
    {
        try {
            $decoded = JWT::decode($jwt, config('jwt.key'), ['HS256']);
        } catch (\Exception $e) {
            return 0;
        }
        return $decoded;
    }
}
